<template>
  <div class="links-page">
    <n-card title="链接管理" class="cute-card">
      <template #header-extra>
        <n-button type="primary" @click="handleCreate" size="small" round>
          创建新链接
        </n-button>
      </template>
      
      <n-data-table
        :columns="columns"
        :data="links"
        :loading="loading"
        :pagination="pagination"
        :row-key="row => row.id"
        :bordered="false"
        striped
      />
      
      <!-- 创建链接模态框 -->
      <n-modal 
        v-model:show="showCreateModal" 
        preset="card" 
        title="创建面试链接" 
        style="width: 600px;"
        :mask-closable="false"
      >
        <n-form
          ref="formRef"
          :model="createForm"
          :rules="rules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          @keydown.enter.prevent
        >
          <n-form-item label="职位名称" path="title">
            <n-input v-model:value="createForm.title" placeholder="请输入职位名称" />
          </n-form-item>
          
          <n-form-item label="职位描述" path="description">
            <n-input
              v-model:value="createForm.description"
              type="textarea"
              placeholder="请输入职位描述"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </n-form-item>
          
          <n-form-item label="职位类型" path="position">
            <n-input v-model:value="createForm.position" placeholder="请输入职位类型，如：全职/实习" />
          </n-form-item>
          
          <n-form-item label="所属部门" path="department">
            <n-input v-model:value="createForm.department" placeholder="请输入所属部门" />
          </n-form-item>
          
          <n-form-item label="过期时间" path="expiresAt">
            <n-date-picker
              v-model:value="createForm.expiresAt"
              type="datetime"
              clearable
              style="width: 100%"
              :is-date-disabled="disablePastDates"
            />
          </n-form-item>
          
          <n-form-item label="最大投递数" path="maxSubmissions">
            <n-input-number
              v-model:value="createForm.maxSubmissions"
              :min="0"
              placeholder="请输入最大投递数，0表示不限制"
              style="width: 100%"
            />
          </n-form-item>
        </n-form>
        
        <template #footer>
          <div class="modal-actions">
            <n-button round @click="handleCancel">取消</n-button>
            <n-button type="primary" round @click="handleSubmit" :loading="creating">
              创建
            </n-button>
          </div>
        </template>
      </n-modal>
      
      <!-- 二维码模态框 -->
      <n-modal 
        v-model:show="showQRModal" 
        preset="card" 
        title="面试链接二维码" 
        style="width: 400px;"
        :mask-closable="false"
      >
        <div class="qrcode-container">
          <QRCodeGen
            v-if="currentLink?.code"
            :value="getFullLink(currentLink.code)"
            :size="200"
            :margin="2"
            :color="{
              dark: '#000000',
              light: '#FFFFFF'
            }"
          />
          
          <div class="link-info">
            <p class="link-url">{{ getFullLink(currentLink?.code) }}</p>
            <n-space>
              <n-button size="small" @click="copyLink" round type="primary">
                复制链接
              </n-button>
              <n-button size="small" @click="showQRModal = false" round>
                关闭
              </n-button>
            </n-space>
          </div>
        </div>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, h, onMounted } from 'vue'
import { 
  useMessage, 
  useDialog, 
  NButton,
  NCard,
  NDataTable,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NDatePicker,
  NSpace,
  NTag
} from 'naive-ui'
import { formatDate, isExpired, getRemainingTime } from '../../utils/date'
import adminApi from '../../api/admin'
import QRCodeGen from '../../components/QRCodeGen.vue'

const message = useMessage()
const dialog = useDialog()
const formRef = ref(null)
const loading = ref(false)
const creating = ref(false)
const links = ref([])
const showCreateModal = ref(false)
const showQRModal = ref(false)
const currentLink = ref(null)

// 创建链接表单
const createForm = reactive({
  title: '',
  description: '',
  position: '',
  department: '',
  expiresAt: null,
  maxSubmissions: 0
})

// 表单验证规则
const rules = {
  title: {
    required: true,
    message: '请输入职位名称',
    trigger: ['blur', 'change']
  },
  description: {
    required: true,
    message: '请输入职位描述',
    trigger: ['blur', 'change']
  },
  position: {
    required: true,
    message: '请输入职位类型',
    trigger: ['blur', 'change']
  },
  department: {
    required: true,
    message: '请输入所属部门',
    trigger: ['blur', 'change']
  },
  expiresAt: {
    required: true,
    validator: (rule, value) => {
      if (!value) {
        return new Error('请选择过期时间')
      }
      return value > Date.now() || new Error('过期时间不能早于当前时间')
    },
    trigger: ['blur', 'change']
  },
  maxSubmissions: {
    type: 'number',
    required: true,
    message: '请输入最大投递数',
    trigger: ['blur', 'change']
  }
}

// 禁用过去的日期
const disablePastDates = (timestamp) => {
  return timestamp < Date.now()
}

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 50],
  onChange: (page) => {
    pagination.page = page
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize
    pagination.page = 1
  }
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 80
  },
  {
    title: '职位名称',
    key: 'title'
  },
  {
    title: '部门',
    key: 'department'
  },
  {
    title: '职位类型',
    key: 'position'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    render(row) {
      return formatDate(row.createdAt)
    }
  },
  {
    title: '过期时间',
    key: 'expiresAt',
    render(row) {
      return formatDate(row.expiresAt)
    }
  },
  {
    title: '状态',
    key: 'status',
    render(row) {
      const expired = isExpired(row.expiresAt)
      return h(NTag, {
        type: expired ? 'error' : 'success',
        round: true,
        bordered: false,
        size: 'small'
      }, {
        default: () => expired ? '已过期' : '有效'
      })
    }
  },
  {
    title: '剩余时间',
    key: 'remainingTime',
    render(row) {
      return getRemainingTime(row.expiresAt)
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
    render(row) {
      return h('div', { class: 'table-actions' }, [
        h(NButton, {
          size: 'small',
          type: 'primary',
          text: true,
          disabled: isExpired(row.expiresAt),
          onClick: () => showQRCode(row),
          style: {
            padding: '4px 12px'
          }
        }, { default: () => '查看二维码' }),
        h(NButton, {
          size: 'small',
          type: 'error',
          text: true,
          onClick: () => confirmDelete(row),
          style: {
            padding: '4px 12px'
          }
        }, { default: () => '删除' })
      ])
    }
  }
]

// 获取所有链接
const getLinks = async () => {
  loading.value = true
  try {
    const res = await adminApi.getLinks()
    links.value = res.data || []
  } catch (error) {
    console.error('获取链接失败:', error)
    message.error('获取链接列表失败')
  } finally {
    loading.value = false
  }
}

// 打开创建模态框
const handleCreate = () => {
  createForm.title = ''
  createForm.description = ''
  createForm.position = ''
  createForm.department = ''
  createForm.expiresAt = null
  createForm.maxSubmissions = 0
  showCreateModal.value = true
}

// 取消创建
const handleCancel = () => {
  createForm.title = ''
  createForm.description = ''
  createForm.position = ''
  createForm.department = ''
  createForm.expiresAt = null
  createForm.maxSubmissions = 0
  showCreateModal.value = false
}

// 提交创建
const handleSubmit = async (e) => {
  e.preventDefault()
  
  formRef.value?.validate(async (errors) => {
    if (errors) {
      return
    }

    if (createForm.expiresAt < Date.now()) {
      message.error('过期时间不能早于当前时间')
      return
    }
    
    creating.value = true
    try {
      await adminApi.createLink({
        title: createForm.title,
        description: createForm.description,
        position: createForm.position,
        department: createForm.department,
        expiresAt: new Date(createForm.expiresAt).toISOString(),
        maxSubmissions: createForm.maxSubmissions
      })
      
      message.success('创建链接成功')
      showCreateModal.value = false
      handleCancel()
      getLinks()
    } catch (error) {
      console.error('创建链接失败:', error)
      message.error('创建链接失败')
    } finally {
      creating.value = false
    }
  })
}

// 显示二维码
const showQRCode = (link) => {
  if (!link || !link.code) {
    message.error('链接信息不完整')
    return
  }
  currentLink.value = link
  console.log(currentLink.value)
  showQRModal.value = true
}

// 确认删除
const confirmDelete = (link) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除此链接吗？删除后无法恢复。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => deleteLink(link.id)
  })
}

// 删除链接
const deleteLink = async (id) => {
  try {
    await adminApi.deleteLink(id)
    message.success('删除成功')
    getLinks()
  } catch (error) {
    console.error('删除链接失败:', error)
    message.error('删除失败')
  }
}

// 复制链接
const copyLink = () => {
  console.log(currentLink.value)
  if (!currentLink.value) return
  const link = getFullLink(currentLink.value.code)
  // 请求剪贴板权限
  navigator.permissions.query({ name: 'clipboard-write' })
    .then(permissionStatus => {
      if (permissionStatus.state === 'granted' || permissionStatus.state === 'prompt') {
        navigator.clipboard.writeText(link)
          .then(() => {
            message.success('链接已复制到剪贴板')
          })
          .catch(() => {
            message.error('复制失败')
          })
      } else {
        message.error('没有剪贴板权限')
      }
    })
    .catch(() => {
      message.error('无法访问剪贴板')
    })
}

// 获取完整链接
const getFullLink = (code) => {
  if (!code) return ''
  const baseUrl = window.location.origin
  return `${baseUrl}/#/apply/${code}`
}

onMounted(() => {
  getLinks()
})
</script>

<style scoped>
.links-page {
  min-height: 100%;
}

.cute-card {
  margin-bottom: 24px;
}

.table-actions {
  display: flex;
  gap: 16px;
  justify-content: flex-start;
}

.table-actions .n-button {
  font-size: 14px;
}

.table-actions .n-button:hover {
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 3px;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-tag.active {
  color: var(--success-color);
  background-color: var(--success-color-suppl);
}

.status-tag.expired {
  color: var(--error-color);
  background-color: var(--error-color-suppl);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
}

.link-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  width: 100%;
  margin-top: 8px;
}

.link-url {
  color: #666;
  font-size: 14px;
  word-break: break-all;
  text-align: center;
  margin: 0;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  width: 100%;
}
</style> 